import { getRequest, postRequest, putRequest, deleteRequest } from '/@/lib/axios';

export const aiApi = {
  // 模型配置
  getModelList: () => getRequest('/api/ai/model-config/list'),
  addModel: (data) => postRequest('/api/ai/model-config/', data),
  updateModel: (data) => putRequest('/api/ai/model-config/', data),
  deleteModel: (id) => deleteRequest(`/api/ai/model-config/${id}`),

  // AI对话
  chat: (data) => postRequest('/api/ai/invoke/chat', data),

  /**
   * 最简流式对话实现，直接读取流并回调 onMessage
   * @param {Object} data - 请求体
   * @param {Function} onMessage - 每次收到新内容时的回调 (chunk: string) => void
   * @returns {Promise<void>} - 结束时 resolve
   */
  chatStream: async (data, onMessage) => {
    const response = await fetch('http://localhost:18080/api/ai/invoke/chat/stream', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + localStorage.getItem('user_token')
      },
      body: JSON.stringify(data),
    });
    if (!response.body) {
      throw new Error('无流式响应');
    }
    const reader = response.body.getReader();
    const decoder = new TextDecoder('utf-8');
    let done = false;
    while (!done) {
      const { value, done: doneReading } = await reader.read();
      done = doneReading;
      if (value) {
        const chunkStr = decoder.decode(value, { stream: true });
        if (onMessage) {
          onMessage(chunkStr);
        }
      }
    }
  },
}; 